package design.proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 *
 *
 * @author yuqi<307530884@qq.com> <2017/3/23>
 * @version 1.0
 * @since 1.0
 */
public class SameMethodClass {

    static class ClassA implements InterA {

        @Override
        public void sayHello() {
            System.out.println("ClassA sayHello");
        }
    }

    static class ClassB implements InterB {

        @Override
        public void sayHello() {
            System.out.println("ClassB sayHello");
        }
    }

    static class InterAProxyHandler implements InvocationHandler {

        private Object o;

        public InterAProxyHandler(Object o) {
            this.o = o;
        }

        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

            Object result = null;
            System.out.println("proxy method call");

            //调用这个方法会出错，因为方法数据InterA,但是被调用对像属于ClassB
//            method.invoke(o, args);
            method.invoke(new ClassA(), args);

            return result;
        }
    }

    public static void main(String[] args) {

        InterB b = new ClassB();

        InterA a = (InterA) Proxy.newProxyInstance(SameMethodClass.class.getClassLoader(),
                new Class[]{InterA.class},
                new InterAProxyHandler(b));

        a.sayHello();

    }

}
